class Solution {
public:
    //用于取每位数平方和
    int getsum(int n)
    {
      int sum = 0;
      while(n)
      {
        int x = n % 10;
        sum += x * x;
        n /= 10;
      }
      return sum;
    }


    bool isHappy(int n) 
    {
      //定义快慢指针
      int slow = n, fast = getsum(n);

      //根据鸽巢原理,两指针必定相遇
      while(fast != slow)
      {
        //迭代
        slow = getsum(slow);
        fast = getsum(getsum(fast));
      }
      //若慢指针为1表示快乐数
      return slow == 1;
    }
};
class Solution {
public:
    int mySqrt(int x) 
    {
        //处理边界问题
        if(x == 0) 
            return 0;
        int left = 1;
        int right = x;

        while(left < right)
        {
            long long mid = left + (right - left + 1) / 2;//防溢出
            
            if(mid*mid <= x)
                left = mid;
            else
                right = mid - 1;
        }
        return left;
    }
};

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) 
    {
        int left = 0, right = nums.size() - 1;
        while(left < right)
        {
            int mid = left + (right-left) / 2;
            if(nums[mid] < target)
                left = mid + 1;
            else
                right = mid;
        }
        //判断插入在最后一个位置后的情况
        if(nums[left] < target)
            return left + 1;
        else 
            return left;
    }
};

class Solution {
public:
    int peakIndexInMountainArray(vector<int>& arr) 
    {
        int left = 0;
        int right = arr.size() - 1;

        while(left < right)
        {
            int mid = left + (right - left + 1) / 2;
            if(arr[mid] > arr[mid - 1]) 
                left = mid;
            else
                right = mid - 1;
        }
        return left;
    }
};

class Solution {
public:
    int findPeakElement(vector<int>& nums) 
    {
        int left = 0, right = nums.size() - 1;
        while(left < right)
        {
            int mid = left + (right - left) / 2;
            if(nums[mid] > nums[mid + 1])
                right = mid;
            else 
                left = mid + 1;
        }
        return left;
    }
};

class Solution {
public:
    int findMin(vector<int>& nums) 
    {
        int left = 0, right = nums.size() - 1;
        while(left < right)
        {
            int mid = left + (right - left) / 2;
            if(nums[mid] > nums[nums.size() - 1])
                left = mid + 1;
            else
                right = mid;
        }
        return nums[left];
    }
};
